/**
 * 每分钟检查数据库，找出需要截图的主播，并向截图程序发出命令
 */

const _ = require('lodash');
const ms = require('ms');

module.exports = {
  schedule: {
    // immediate: true,
    cron: '0 */1 * * * *', // 每分钟
    // cron: '* * * * * *', // 每秒运行，测试用
    type: 'all', // 指定一个 worker 执行
    env: ['prod'],// 在prod环境才执行
  },
  async task(ctx) {


    //检查有没有截图程序
    let socketsKey = Object.keys(ctx.app.io.sockets.sockets);
    console.log('每分钟截图任务，截图程序Keys情况 : ' + socketsKey.join(','));
    // console.log('pid: ' + process.pid, '截图程序数量', socketsKey.length);
    if (socketsKey.length === 0)
      return;

    const now = Date.now();
    const app = ctx.app;
    const {lte, gte} = app.Sequelize.Op;
    const {DetailAnchor, DetailAnchorSchedule} = app.model;
    const schedules = await DetailAnchorSchedule.findAll({
      where: {start: {[lte]: now}, end: {[gte]: now}},
      include: [
        {model: DetailAnchor, as: 'anchor', attributes: ['url']},
      ],
    });
    const anchors = {};
    schedules.forEach(schedule => {
      //计算上一次截图时间
      if (schedule.last) {
        const inLoopTime = (now - new Date(schedule.last).getTime()) <
            ms(schedule.loop + 'm');
        // console.log('loop time', now - new Date(schedule.last).getTime(), ms(schedule.loop + 'm'));
        if (inLoopTime)
          return;
      }
      if (_.isEmpty(schedule.anchor) || _.isEmpty(schedule.anchor.url))
        return;

      //下面是防止同一个主播多次重复截图的逻辑

      //还没有任务的主播
      if (!anchors.hasOwnProperty(schedule.anchor_id)) {
        anchors[schedule.anchor_id] = {
          url: schedule.anchor.url,
          anchor_id: schedule.anchor_id,
          platform_id: schedule.platform_id,
          schedule_id: [schedule.id],
        };
      } else {//主播已经有截图任务了，叠加 schedule id
        anchors[schedule.anchor_id].schedule_id.push(schedule.id);
      }
      DetailAnchorSchedule.update({last: now}, {where: {id: schedule.id}});
    });
    if (_.isEmpty(anchors))
      return;

    //给截图程序发送截图命令
    Object.values(anchors).forEach(anchor => {
      let random = _.random(0, socketsKey.length - 1);
      let socket = ctx.app.io.sockets.sockets[socketsKey[random]];
      socket.emit('screenshot_anchor', anchor);
    });
  },
};